<template>
  <div>
    <form class="card comment-form">
      <div class="card-block">
        <textarea class="form-control" placeholder="Write a comment..." rows="3" v-model="comment.body"></textarea>
      </div>
      <div class="card-footer">
        <img :src="user.image" class="comment-author-img" />
        <button class="btn btn-sm btn-primary" @click.prevent="postComment">Post Comment</button>
      </div>
    </form>

    <div class="card" v-for="comment in comments" :key="comment.id">
      <div class="card-block">
        <p class="card-text">{{ comment.body }}</p>
      </div>
      <div class="card-footer">
       <router-link :to="{
            name:'profile',
            params:{
                username: comment.author.username
            }
        }" class="comment-author">
          <img :src="comment.author.image" class="comment-author-img" />
        </router-link>
        &nbsp;
        <router-link :to="{
            name:'profile',
            params:{
                username: comment.author.username
            }
        }" class="comment-author">{{ comment.author.username }}</router-link>
        <span class="date-posted">{{ comment.createdAt | date('MMM DD, YYYY') }}</span>
      </div>
    </div>

  </div>
</template>
<script>
import { getComments, addComments } from "@/api/article";
import { mapState } from 'vuex'
export default {
  name: "ArticleComments",
  props: {
    article: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      comments: [],
      comment:{
          body:''
      }
    };
  },
  computed:{
      ...mapState(["user"]),
  },
  async mounted() {
    const { data } = await getComments(this.article.slug);
    this.comments = data.comments
  },
  methods:{
       async postComment(){
        const { data } =  await addComments(this.article.slug,this.comment)
        this.comment.body = ''
        this.comments.splice(0,0,data.comment)
      }
  }
};
</script>